<?php

namespace App\Livewire;

use App\Events\Sing;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Livewire\Attributes\Computed;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;
use Faker\Factory;
use function Symfony\Component\String\s;

#[Title('首页')]
class IndexPage extends Component
{

    public $messageList = [];

    public $memberList = [];

    public $profile = [];

    public function mount()
    {


        $this->messageList = Cache::rememberForever('message', function () {
            return [];
        });
        $this->memberList = Cache::rememberForever('memberList', function () {
            return [];
        });

        $this->initProfile();


    }
    #[Computed]
    public function userList()
    {

        return  collect($this->memberList)->sortBy('active_time',SORT_DESC)->take(10);
    }
    #[On('echo:channel-name,Sing')]
    public function notifyMessage()
    {
          $this->messageList = Cache::get('message');
         $this->dispatch('load-message');
    }
    public function initProfile(): void
    {
        $this->profile = session('profile');
        if (!$this->profile) {
            $profile =  [
                'ip' => request()->ip(),
                'name'=> Factory::create('zh_CN')->name(),
                'uuid' => Str::replace('-','',Str::uuid()->toString()) ,
                'avatar'=> '/default.jpg',
                'active_time'=>Carbon::now()
            ];

            session(['profile'=> $profile]);
            $this->memberList = collect($this->memberList)->push($profile);
            Cache::set('memberList', $this->memberList);
            $this->profile = $profile;
        }

    }

    public function updateAvatar($avatar)
    {
        $this->profile['avatar'] = $avatar;
        $this->profile['active_time'] = Carbon::now();
        session(['profile' => $this->profile]);
        $this->memberList = collect($this->memberList)->map(function ($item){
            if ($item['uuid'] == $this->profile['uuid']) {
                $item = $this->profile;
            }
            return $item;
        });
        Cache::set('memberList', $this->memberList);
    }
    public function render()
    {
        return view('livewire.index');
    }

    public function submitData($message)
    {
        Sing::dispatch($this->profile['name'],$message);
        $this->messageList = collect($this->messageList)->push([
            'name'=>$this->profile['name'],
            'avatar'=> $this->profile['avatar'],
            'message'=>$message,
        ]);
        Cache::set('message', $this->messageList);
    }
}
